package com.coocaa.ops.plus.core.base.interceptor;


import com.coocaa.ops.common.tool.http.HttpSessionUtil;
import com.coocaa.ops.plus.core.base.annotation.MyAuth;
import com.coocaa.ops.plus.core.base.constant.PlusConstant;
import com.coocaa.ops.plus.core.base.enums.MyRoleEnums;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author bijiahao
 * @date : 2018/1/19.
 * @description 定义扩展模块 权限拦截器
 */
public class MyAuthInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            return true;
        }
        MyAuth myAuth = ((HandlerMethod) handler).getMethodAnnotation(MyAuth.class);
        if (myAuth == null || myAuth.validAuth() == false || myAuth.validLogin() == false) {
            return true;
        }
        MyRoleEnums[] roleEnums = myAuth.hasRoles();
        String tokenVal = (String) HttpSessionUtil.getSessionValue(request, PlusConstant.SESSION_TOKEN);
        for (MyRoleEnums myRole : roleEnums) {
            if (myRole.name().equalsIgnoreCase(tokenVal)) {
                return true;
            }
        }
        //返回到扩展模块 登录界面
        response.sendRedirect("/myExtend/index.html");
        return false;
    }
}
